<template>
  <div class="app-container">
    <el-form
      class="searchform"
      :model="queryParams"
      ref="queryParams"
      size="small"
      label-width="80px"
    >
      <el-row :gutter="20">
        <el-col :span="5">
          <el-form-item label="单位名称" label-width="90px">
            <m-select
              v-model="queryParams.entrustOrganizationId"
              :dimStr="queryParams.organizationName"
              placeholder="输入文字检索查询"
              style="width: 100%"
              filterable
              clearable
              :lists="entrustOrganizationSelect"
              lists_label="organizationName"
              lists_value="entrustOrganizationId"
              lists_key="entrustOrganizationId"
              :total="orgTotal"
              :pageSize="10"
              @handleChange="listeningEvent"
            >
            </m-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="合同编号">
            <el-input
              v-model="queryParams.agreementNumber"
              placeholder="请输入"
              clearable
              @keyup.enter.native="getList()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="是否收费">
            <el-select
              v-model="queryParams.charge"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="(item, index) in dict.type.is_or_no"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="签订时间">
            <el-date-picker
              v-model="queryParams.formDate"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
              clearable
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label-width="0">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getList()"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="reset()"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="tableoperation">
      <el-button
        type="primary"
        icon="el-icon-plus"
        size="mini"
        @click="openDialog()"
        >添加</el-button
      >
      <!-- <el-button type="primary" icon="el-icon-plus" size="mini" @click="openSignature()">测试合同dailog</el-button> -->
    </div>

    <el-table
      v-loading="loading"
      :data="entrustAgreementList"
      :height="height - 400 + 'px'"
      @row-dblclick="(row) => openDialog(row, '3')"
    >
      <el-table-column label="序号" type="index" width="50" align="center" />
      <el-table-column label="合同编号" align="center" prop="agreementNumber" />
      <el-table-column
        label="委托单位"
        align="center"
        prop="organizationName"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="检测项目" align="center" width="200">
        <template slot-scope="scope">
          <span @click="openProj(scope.row)" class="viewNumber">{{
            scope.row.testItemNum
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否收费" align="center" width="200">
        <template slot-scope="{ row }">
          <dict-tag
            :options="dict.type.is_or_no"
            :value="row.charge"
          ></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="合同状态" align="center" width="200">
        <template slot-scope="{ row }">
          <dict-tag
            :options="dict.type.agreement_state"
            :value="row.agreementState"
          ></dict-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="合同开始时间"
        align="center"
        prop="beginTime"
        width="120"
      />
      <el-table-column
        label="合同结束时间"
        align="center"
        prop="endTime"
        width="120"
      />
      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="{ row }">
          <el-button @click.native.prevent="openDialog(row)" type="text">
            编辑
          </el-button>
          <el-button
            v-if="row.renew"
            @click.native.prevent="openDialog(row, '4')"
            type="text"
          >
            续签
          </el-button>
          <el-button
            @click.native.prevent="handleDelete(row)"
            type="text"
            style="color: #f32d2d"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      @close="closeDialog"
      v-dialogDrag="true"
    >
      <el-form
        :model="form"
        :disabled="status == '3'"
        :rules="rules"
        ref="form"
        size="small"
        label-width="120px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="单位名称" prop="entrustOrganizationId">
              <el-input
                v-if="status == '2' || status == '3' || status == '4'"
                v-model="form.organizationName"
                disabled
              />
              <m-select
                v-else
                v-model="form.entrustOrganizationId"
                placeholder="请选择"
                filterable
                clearable
                @change="changeOrganization"
                style="width: 100%"
                :lists="entrustOrganizationSelect"
                lists_label="organizationName"
                lists_value="entrustOrganizationId"
                lists_key="entrustOrganizationId"
                :total="orgTotal"
                :pageSize="10"
                @handleChange="listeningEvent"
              >
              </m-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审批流程" prop="tasksContractId">
              <el-input
                v-if="status == '2' || status == '3' || status == '4'"
                v-model="form.tasksContractName"
                disabled
              />
              <el-select
                v-else
                v-model="form.tasksContractId"
                @change="changeContract"
                placeholder="请选择"
                filterable
                clearable
                style="width: 100%"
              >
                <el-option
                  :label="item.tasksContractName"
                  :value="item.tasksContractId"
                  v-for="(item, index) in tasksContractBindListSelect"
                  :key="index"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同编号" prop="agreementNumber">
              <el-input
                v-model="form.agreementNumber"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="签订金额(元)" prop="signAmount">
              <el-input
                v-model="form.signAmount"
                :placeholder="status != '3' ? '请输入' : ''"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同开始日期" prop="beginTime">
              <el-date-picker
                style="width: 100%"
                v-model="form.beginTime"
                value-format="yyyy-MM-dd"
                type="date"
                :picker-options="pickerOptionsF"
                placeholder="请选择"
                @change="handleChangeEndTime"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同结束日期" prop="endTime">
              <el-date-picker
                style="width: 100%"
                v-model="form.endTime"
                value-format="yyyy-MM-dd"
                type="date"
                :picker-options="pickerOptionsS"
                placeholder="请选择"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="8">
						<el-form-item label="是否发起任务" prop="isLaunch">
							<el-select
								v-model="form.isLaunch"
								placeholder="请选择"
								style="width: 100%">
								<el-option
									v-for="(item,index) in isLaunchList"
									:label="item.label"
									:value="item.value"
									:key="index">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col> -->
          <el-col :span="8">
            <el-form-item label="是否收费" prop="charge">
              <el-select
                v-model="form.charge"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in dict.type.is_or_no"
                  :label="item.label"
                  :value="item.value"
                  :key="index"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同状态" prop="agreementState">
              <el-select
                v-model="form.agreementState"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in dict.type.agreement_state"
                  :label="item.label"
                  :value="parseInt(item.value)"
                  :key="index"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item
              :label="status == '3' ? '查看附件' : '上传附件'"
              prop="agreementFileOssId"
            >
              <el-input v-model="form.agreementFileOssId" v-if="false" />
              <el-upload
                ref="upload"
                :action="upload.url"
                :headers="upload.headers"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleFileSuccessSecond"
                :before-upload="beforeAvatarUpload"
                :file-list="fileList"
                multiple
              >
                <el-button
                  v-if="status != '3'"
                  icon="el-icon-upload"
                  size="mini"
                  plain
                  type="primary"
                  >上传文件</el-button
                >
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                type="textarea"
                rows="3"
                maxlength="100"
                show-word-limit
                v-model="form.remark"
                :placeholder="status != '3' ? '请输入' : ''"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer">
        <el-button type="primary" v-if="status != '3'" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 检测项目弹框 -->
    <el-dialog
      title="检测项目"
      :visible.sync="dialogVisibleProj"
      :close-on-click-modal="false"
      width="1500px"
      v-dialogDrag="true"
    >
      <el-table v-if="projectType == 1" height="400" :data="projectList">
        <el-table-column
          label="设备名称"
          align="center"
          prop="entrustEquipmentName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="台件数"
          align="center"
          prop="equipmentCount"
          width="100"
        />
        <el-table-column label="场所" align="center" prop="location" />
        <el-table-column label="生产厂家" align="center" prop="manufacturer" />
        <el-table-column label="采购日期" align="center" width="100">
          <template slot-scope="{ row }">
            {{ parseTime(row.purchaseTime, "{y}-{m}-{d}") }}
          </template>
        </el-table-column>
        <el-table-column
          label="规格型号"
          align="center"
          prop="specificationModel"
        />
        <el-table-column label="检测类型" align="center">
          <template slot-scope="scope">
            <span
              class="cusinspectionTypeName"
              v-for="(item, index) in scope.row.cusinspectionTypeName"
              :key="index"
              >{{ item }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="检测项目"
          align="center"
          prop="inspectionCategory"
        />
      </el-table>

      <el-table v-if="projectType == 2" height="400" :data="projectList">
        <el-table-column
          label="设备类型"
          align="center"
          prop="entrustEquipmentTypeName"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="台件数" align="center" prop="num" />
        <el-table-column label="金额" align="center" prop="amount">
          <template slot-scope="scope">
            <span>{{
              scope.row.amount &&
              scope.row.num &&
              (scope.row.amount * scope.row.num) / 100
            }}</span>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer">
        <el-button @click="dialogVisibleProj = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  entrustAgreementList,
  entrustAgreementExport,
  entrustAgreementDetail,
  entrustAgreementRenew,
  entrustAgreementAdd,
  entrustAgreementEdit,
  entrustAgreementDelete,
  tasksContractBindList,
  queryDetectionProjectList,
  getGenAgreementNumber,
} from "@/api/person/entrustAgreement";
import {
  entrustOrganizationListing,
  entrustOrganizationList,
} from "@/api/person/entrustOrganization";
import { getInspectionList } from "@/api/slides/contractTask";
import { listOss, listByIds, delOss } from "@/api/system/oss";
import { getToken } from "@/utils/auth";
import MSelect from "@/components/mSelect";
import { parseTime } from "@/utils/ruoyi";

export default {
  name: "EntrustAgreement",
  dicts: ["sys_user_sex", "is_or_no", "agreement_state"],
  components: { MSelect },
  data() {
    return {
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      rules: {
        entrustOrganizationId: [
          { required: true, message: "单位名称不能为空", trigger: "blur" },
        ],
        // tasksContractId: [
        //   { required: true, message: "审批流程不能为空", trigger: "blur" },
        // ],
        agreementNumber: [
          { required: true, message: "合同编号不能为空", trigger: "blur" },
        ],
        // signAmount: [
        //   { required: true, message: "签订金额不能为空", trigger: "blur" },
        // 	{
        //     pattern: /^\d+(.\d+)?$/,
        //     message: "请输入正确的格式",
        //     trigger: "blur"
        //   }
        // ],
        beginTime: [
          { required: true, message: "合同开始日期不能为空", trigger: "blur" },
        ],
        endTime: [
          { required: true, message: "合同结束日期不能为空", trigger: "blur" },
        ],
        // agreementFileOssId: [
        //   { required: true, message: "请上传附件", trigger: "blur" },
        // ],
      },
      // 视图高度
      height: document.documentElement.clientHeight,
      // 合同列表
      entrustAgreementList: [],
      activeName: "0",
      total: 0,
      deptOptions: [],
      dialogVisible: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken(),
          "Content-Disposition": "inline",
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/oss/upload",
      },
      status: null,
      title: null,
      // 委托单位下拉框
      entrustOrganizationSelect: [],
      // 上传的文件列表
      fileList: [],
      url: null,
      // 任务下拉框
      tasksContractBindListSelect: [],
      dialogVisibleProj: false,
      // 项目列表
      projectList: [],
      projectType: null,
      // 检测类型列表
      inspectionList: [],
      // 日期校验
      pickerOptionsF: {
        disabledDate: (time) => {
          return time.getTime() > new Date(this.form.endTime).getTime();
        },
      },
      pickerOptionsS: {
        disabledDate: (time) => {
          return time.getTime() < new Date(this.form.beginTime).getTime();
        },
      },
      isLaunchList: [
        {
          label: "是",
          value: true,
        },
        {
          label: "否",
          value: false,
        },
      ],
      // 单位查询数据
      organizationQueryData: {
        organizationName: "", //单位名称模糊查询
        pageNum: 1, //页码
        pageSize: 10, //每页展示的条数
      },
      orgTotal: 0,
    };
  },
  created() {
    // 首页合同预警跳转而来 自动输入单位名称
    if (this.$route.params.isTodo) {
      // console.log(this.$route.params);
      this.queryParams.organizationName = this.$route.params.organizationName;
      this.$set(
        this.queryParams,
        "entrustOrganizationId",
        this.$route.params.entrustOrganizationId
      );
    }

    this.getList();
    this.getInspectionListing();
  },
  methods: {
    openSignature() {},
    // 默认一年合同
    handleChangeEndTime(val) {
      const date = new Date(val);
      date.setFullYear(date.getFullYear() + 1);
      date.setDate(date.getDate() - 1);
      let newDate = parseTime(date, "{y}-{m}-{d}");
      this.$set(this.form, "endTime", newDate);
    },
    // 获取单位下拉框
    listeningEvent(e) {
      let { queryName, pageNum, pageSize, type } = e;
      if (type == "scroll" && pageNum == this.organizationQueryData.pageNum)
        return;
      this.organizationQueryData.organizationName = queryName;
      this.organizationQueryData.pageNum = pageNum;
      this.organizationQueryData.pageSize = pageSize;
      entrustOrganizationList(this.organizationQueryData).then((response) => {
        if (type == "scroll") {
          this.entrustOrganizationSelect.push(...response.rows);
        } else {
          this.entrustOrganizationSelect = response.rows;
        }
        this.orgTotal = response.total;
      });
    },
    // 获取检测类型下拉框
    getInspectionListing() {
      getInspectionList().then((response) => {
        this.inspectionList = response.rows;
      });
    },
    // 获取合同列表
    getList() {
      this.queryParams.beginTimeStart =
        this.queryParams.formDate && this.queryParams.formDate[0];
      this.queryParams.beginTimeEnd =
        this.queryParams.formDate && this.queryParams.formDate[1];
      let queryParams = { ...this.queryParams };
      delete queryParams.formDate;
      this.loading = true;
      entrustAgreementList(queryParams)
        .then((response) => {
          this.entrustAgreementList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch((response) => {
          this.loading = false;
        });
    },
    // 打开对话框
    async openDialog(row, status) {
      this.resetForm("form");
      if (row) {
        entrustAgreementDetail(row.agreementId).then((response) => {
          this.form = response.data || {};
          if (this.form.signAmount) {
            this.form.signAmount /= 100;
          }
          if (this.status == "4") {
            this.$set(this.form, "remark", this.form.agreementNumber);
            this.$set(this.form, "agreementNumber", null);
            this.$set(this.form, "isLaunch", false);
            this.$set(this.form, "agreementFileOssId", null);
            this.$set(this.form, "beginTime", row.renewBeginTime);
            this.$set(this.form, "endTime", row.renewEndTime);
          }
          if (this.form.agreementFileOssId) {
            listByIds(this.form.agreementFileOssId).then((response) => {
              this.fileList = response.data;
              this.fileList.forEach((item) => {
                item.name = item.originalName;
              });
            });
          }
          this.dialogVisible = true;
        });
        if (status == "3") {
          this.status = "3";
          this.title = "查看合同";
        } else if (status == "4") {
          this.status = "4";
          this.title = "续签合同";
        } else {
          this.status = "2";
          this.title = "编辑合同";
        }
      } else {
        let { data } = await getGenAgreementNumber();
        this.form = {
          agreementNumber: data,
          agreementFileOssId: null,
          charge: "1",
          isLaunch: true,
        };
        this.fileList = [];
        this.status = "1";
        this.title = "添加合同";
        this.dialogVisible = true;
      }
    },
    // 提交按钮
    submitForm() {
      this.form.agreementFileOssId = this.fileList
        .map((item) => {
          if (item.ossId) {
            return item.ossId; /* 回显的列表格式 */
          } else if (item.response.data) {
            return item.response.data.ossId; /* 新上传的列表格式 */
          }
        })
        .join(",");
      this.$refs["form"].validate((valid) => {
        if (!valid) return;
        let form = { ...this.form };
        form.signAmount *= 100;
        if (this.status == "1") {
          entrustAgreementAdd(form).then((response) => {
            this.$modal.msgSuccess("添加成功");
            this.dialogVisible = false;
            this.getList();
          });
        } else if (this.status == "2") {
          entrustAgreementEdit(form).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.dialogVisible = false;
            this.getList();
          });
        } else if (this.status == "4") {
          entrustAgreementRenew(form).then((response) => {
            this.$modal.msgSuccess("续签成功");
            this.dialogVisible = false;
            this.getList();
          });
        }
      });
    },
    // 删除
    handleDelete(row) {
      this.$modal
        .confirm(
          `是否确认删除委托单位为${row.entrustOrganizationId}的合同[${row.agreementNumber}]？`
        )
        .then(() => {
          this.loading = true;
          return entrustAgreementDelete(row.agreementId);
        })
        .then(() => {
          this.loading = false;
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 检测项目详情
    openProj(row) {
      queryDetectionProjectList({ agreementId: row.agreementId }).then(
        (response) => {
          this.projectList = response.data.rows;
          this.projectType = response.data.type;
          if (this.projectType == 1) {
            this.projectList.forEach((item) => {
              let arr = item.inspectionTypeId.split(",");
              item.cusinspectionTypeName = [];
              arr.forEach((id) => {
                let obj = this.inspectionList.find((it) => {
                  return it.inspectionTypeId == id;
                });
                if (obj) {
                  item.cusinspectionTypeName.push(obj.typeName);
                }
              });
            });
          }
          this.dialogVisibleProj = true;
        }
      );
    },
    // 表单重置
    reset() {
      (this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      }),
        this.resetForm("queryParams");
      this.getList();
    },
    // 更改委托单位
    changeOrganization(val) {
      this.$set(this.form, "tasksContractId", null);
      this.$set(this.form, "tasksContractName", null);
      if (val) {
        tasksContractBindList({ entrustOrganizationId: val }).then(
          (response) => {
            this.tasksContractBindListSelect = response.data;
          }
        );
      }
    },
    // 更改审批流程
    changeContract(val) {
      console.log("更改审批流程", val);
      this.$set(this.form, "signAmount", null);
      let obj = this.tasksContractBindListSelect.find(
        (item) => item.tasksContractId == val
      );
      if (obj) {
        this.$set(this.form, "signAmount", obj.amount / 100);
        if (obj.agreementNumber) {
          this.$set(this.form, "agreementNumber", obj.agreementNumber);
        }
      }
    },
    // 文件移除
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    // 弹框文件预览
    handlePreview(file, fileList) {
      console.log("handlePreview", file, fileList);
      let url = null;
      // 上传时
      if (file.response && file.response.data) {
        window.open(file.response.data.url, "PDF", "");
      } else if (file.url) {
        window.open(file.url, "PDF", "");
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 文件上传成功处理
    handleFileSuccessSecond(response, file, fileList) {
      if (response.code == 500) {
        this.$modal.msgWarning(response.msg);
      }
      this.fileList = fileList;
      this.upload.open = false;
      this.upload.isUploading = false;
    },
    // 上传前
    beforeAvatarUpload(file) {
      let isPDF = file.type === "application/pdf";
      if (!isPDF) {
        this.$message.warning("仅支持pdf格式，请重新上传!");
      }
      return isPDF;
    },
    closeDialog() {
      this.$refs.upload.clearFiles();
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-upload-list.is-disabled {
  margin-top: -40px;
}
::v-deep .el-upload-list {
  display: inline-block;
  vertical-align: bottom;
  transform: translateY(-2px);
}

::v-deep .el-textarea__inner {
  resize: none;
}
::v-deep .el-form {
  margin-left: -20px;
}
.viewNumber {
  color: #2a72ee;
  cursor: pointer;
  &:hover {
    text-decoration: underline;
  }
}
.cusinspectionTypeName {
  margin-right: 20px;
  &:nth-last-child(1) {
    margin-right: 0;
  }
}
</style>
